<template>
  <div class="app-container home">
    <div class="bg_fff mb_12 pl_14">
      <breadcrumb />
    </div>
    <div class="bg_fff p_14 pb_0 mb_12">
      <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
        <el-form-item label="角色组ID" prop="keyword">
          <el-input
            v-model="queryParams.keyword"
            placeholder="请输入角色组名称/ID"
            clearable
            @keyup.enter.native="handleQuery"
          />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="queryParams.status" placeholder="请选择状态" clearable @change="handleQuery">
            <el-option
              v-for="dict in statusList"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
          <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div class="bg_fff p_10 listbody">
      <div class="flexrowbetween flexwrapper mb_15" style="align-items: flex-start">
        <div class="flex">
          <el-button plain type="primary" size="mini" @click="handleAdd">添加</el-button>
        </div>
        <div>
          <!-- <el-button plain type="primary" size="mini" @click="handleAdd">导出</el-button> -->
        </div>
      </div>
      <el-table
        v-loading="loading"
        :data="tableData"
        ref="tablelayout"
        class="commtable"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55"></el-table-column>
        <el-table-column label="序号" type="index" align="center">
        <template slot-scope="scope">
          <span>{{(queryParams.page - 1) * queryParams.num + scope.$index + 1}}</span>
        </template>
      </el-table-column>
        <el-table-column
          align="center"
          label="用户ID"
          prop="id"
          width="120"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          align="center"
          label="用户名称"
          prop="user_login"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          align="center"
          label="昵称"
          prop="user_nickname"
          :show-overflow-tooltip="true"
        ></el-table-column>
        <el-table-column
          align="center"
          label="手机号"
          prop="mobile"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span>{{scope.row.mobile || '-'}}</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="所属级别"
          prop="role_user.role.name"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            <span v-if="scope.row.role&&scope.row.role.length>0" v-for="(item,index) in scope.row.role">{{item.roleName}}
             <template v-if="index <scope.row.role.length-1">,</template>
              </span>
            <span v-else>-</span>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="Email"
          prop="name"
          :show-overflow-tooltip="true"
        >
          <template slot-scope="scope">
            {{scope.row.user_email || '-'}}
          </template>
        </el-table-column>
        <el-table-column label="状态" align="center" :show-overflow-tooltip="true">
          <template slot-scope="scope">
            <el-tag v-if="scope.row.user_status == 1" type="success" class="tag_success">正常</el-tag>
            <el-tag v-else type="danger" class="tag_danger">异常</el-tag>
          </template>
        </el-table-column>
        <el-table-column
          align="center"
          label="最后登录"
          :show-overflow-tooltip="true"
        >
        <template slot-scope="scope">
          {{parseTime(scope.row.last_login_time) || '-'}}
        </template>
        </el-table-column>
        <el-table-column
          prop="created_at"
          label="操作"
          width="160"
          fixed="right"
          align="center"
        >
          <template slot-scope="scope">
            <div class="flexcenter btnflex">
              <!-- <div
                class="commhover btn_green c_fff mr_10"
                @click="handleUpdate(scope.row)"
              >
                <i class="el-icon-edit f-14"></i> 编辑
              </div> -->
              <div class="commhover mr_10"
                  @click="handleUpdate(scope.row)" v-hasPermi="['admin:edit']">
                <el-tooltip class="item" effect="dark" content="编辑" placement="top-start">
                  <i class="el-icon-edit-outline f-24 c_primary"></i>
                </el-tooltip>
              </div>
              <div class="commhover mr_10"  v-if="scope.row.user_status == 1" @click="handleDelete(scope.row)" v-hasPermi="['admin:stop']">
                <el-tooltip class="item" effect="dark" content="暂停" placement="top-start">
                  <svg-icon class-name="f-24 " icon-class="disable" />
                </el-tooltip>
              </div>

              <div class="commhover mr_10"  v-if="scope.row.user_status == 0" @click="handleStart(scope.row)" v-hasPermi="['admin:open']">
                <el-tooltip class="item" effect="dark" content="启用" placement="top-start">
                  <svg-icon class-name="f-24 c_12A000" icon-class="start" />
                </el-tooltip>
              </div>
              <!-- <div v-if="scope.row.user_status == 1"
                class="commhover btn_yellow c_fff"
                @click="handleDelete(scope.row)"
              >
                <i class="el-icon-delete f-14"></i> 暂停
              </div> -->
              <!-- <div v-if="scope.row.user_status == 0"
                class="commhover btn_yellow c_fff"
                @click="handleStart(scope.row)"
              >
                <i class="el-icon-delete f-14"></i> 启用
              </div> -->
            </div>
          </template>
        </el-table-column>
      </el-table>
      <pagination
        v-show="total > 0"
        :total="total"
        :page.sync="queryParams.page"
        :limit.sync="queryParams.num"
        @pagination="getList"
      />
    </div>
    <el-dialog
      :title="title"
      :visible.sync="open"
      width="680px"
      class="dialogheaderbg"
      :before-close="handleCloseAdd"
      :close-on-click-modal='false'
    >
      <el-form ref="form" :model="form" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="所属级别" prop="role_id">
          <el-select clearable v-model="form.role_id" placeholder="请选择所属级别" style="width:100%">
            <el-option v-for="(item, index) in rolesList" :key="index" :value="item.id" :label="item.roleName" />
          </el-select>
        </el-form-item>
        <el-form-item label="用户名" prop="name">
          <el-input v-model="form.name" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="Email" prop="email">
          <el-input v-model="form.email" placeholder="请输入邮箱" />
        </el-form-item>
        <el-form-item label="昵称" prop="nickname">
          <el-input v-model="form.nickname" placeholder="请输入昵称" />
        </el-form-item>
        <el-form-item label="密码" :prop="form.id == undefined?'password':''">
          <el-input v-model="form.password" placeholder="请输入密码" show-password />
        </el-form-item>
        <el-form-item label="手机号" prop="phone">
          <el-input v-model="form.phone" placeholder="请输入手机号"  />
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio-group v-model="form.status">
            <el-radio :label="1">正常</el-radio>
            <el-radio :label="0">暂停</el-radio>
          </el-radio-group>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="handleCloseAdd">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { mapState } from "vuex";
import { validPhone } from '@/utils/validate';
import { getUserIndex,userAdd,getUserInfo,userEdit,userDel,openStatus } from '@/api/roles'
export default {
  data() {
    return {
      statusList:[{value:1,label:'正常'},{value:0,label:'暂停'}],
      queryParams: {
        page: 1,
        num: 10,
        keyword:undefined,
        status: undefined
      },
      total: 1,
      loading: false,
      tableData: [],
      checkedOption: [],
      isrefresh: false,
      selectoptions: [
        { id: 1, label: "ID" },
        { id: 2, label: "用户名" },
        { id: 3, label: "昵称" },
        { id: 4, label: "所属级别" },
        { id: 5, label: "Email" },
        { id: 6, label: "状态" },
        { id: 7, label: "最后登录" },
      ],
      rolesList:[],
      multiple: true,
      title: "",
      // 是否显示弹出层
      open: false,
      form: {},
      // 表单校验
      rules: {
        role_id: [{ required: true, message: "请选择所属级别", trigger: "change" }],
        name: [{ required: true, message: "请输入用户名", trigger: "blur" }],
        email:[{ required: true,type:'email', message: "请输入正确的邮箱地址", trigger: "blur" }],
        nickname: [{ required: true, message: "请输入昵称", trigger: "blur" }],
        phone: [{ required: true, validator: validPhone, trigger: "blur" }],
        password: [{ required: true, message: "请输入密码", trigger: "blur" }],
        status:[{ required: true, message: "请选择状态", trigger: "change" }]
      },
    };
  },

  props: {
    type: {
      type: Number,
      default: 1,
    },
  },

  computed: {
    ...mapState({
      adminOption: (state) => state.paramsoption.adminOption,
    }),
  },

  created() {
    let adminOption = JSON.parse(localStorage.getItem("adminOption"));
    if (adminOption) {
      this.changeSelect(adminOption);
    }
    this.checkedOption = this.adminOption;
    this.getList()
  },

  methods: {
    getList() {
      this.loading = true;
      let params = {
        page: this.queryParams.page,
        num: this.queryParams.num
      }
      if(this.queryParams.keyword){
        params.keyword = this.queryParams.keyword
      }
      if(this.queryParams.status||this.queryParams.status==0){
        params.status = this.queryParams.status
      }
      getUserIndex(params).then((response) => {
        this.tableData = response.data.list;
        this.total = response.data.count;
        this.loading = false;
      });
      this.isrefresh = false;
      this.loading = false;
    },

    changeSelect(arr) {
      this.$store.commit("SET_ADMINOPTION", arr);
      this.$nextTick(() => {
        //在数据加载完，重新渲染表格
        this.$refs.tablelayout && this.$refs.tablelayout.doLayout();
      });
    },

    handleQuery() {
      this.queryParams.page = 1;
      this.getList();
    },

    resetQuery() {
      this.isrefresh = true;
      this.resetForm("queryForm");
      this.handleQuery();
    },

    handleSelectionChange(selection) {
      this.rowids = selection.map((item) => item.id);
      this.multiple = !selection.length;
    },

    reset() {
      this.form = {
        id:undefined,
        role_id: undefined,
        name: undefined,
        nickname:undefined,
        email:undefined,
        password:undefined,
        phone:undefined,
        status: 1
      };
      this.resetForm("form");
    },

    getRoles(){
      this.getDicts('/manager/admin_Rbac/roleAllList').then(res=>{
        this.rolesList = res.data
      })
    },

    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.getRoles()
      this.open = true;
      this.title = "添加";
    },

    handleCloseAdd() {
      this.open = false;
    },

    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      this.getRoles()
      getUserInfo({id:row.id}).then(res=>{
        let data = res.data
        this.form.id = data.id
        this.form.role_id = data.role_user?data.role_user.role_id:null,
        this.form.name = data.user_login
        this.form.nickname = data.user_nickname
        this.form.email = data.user_email
        this.form.status = data.user_status
        this.form.phone = data.mobile
        this.open = true;
        this.title = "编辑";
      })
    },

    /** 提交按钮 */
    submitForm: function () {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            userEdit(this.form).then((response) => {
              this.$modal.msgSuccess("编辑成功");
              this.open = false;
              this.getList();
            });
          } else {
            userAdd(this.form).then((response) => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    /** 暂停按钮操作 */
    handleDelete(row) {
      const infoIds = row.id;
      this.$modal
        .confirm('是否确认暂停编号为"' + infoIds + '"的用户？')
        .then(function () {
          return userDel({id:infoIds});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("暂停成功");
        })
        .catch(() => {});
    },

    handleStart(row) {
      const infoIds = row.id;
      this.$modal
        .confirm('是否确认启用编号为"' + infoIds + '"的用户？')
        .then(function () {
          return openStatus({id:infoIds});
        })
        .then(() => {
          this.getList();
          this.$modal.msgSuccess("启用成功");
        })
        .catch(() => {});
    },
  },
};
</script>

<style lang="scss" scoped>
.iconbox {
  width: 32px;
  height: 32px;
  border: 1px solid #eee;
  border-radius: 2px;
}
</style>
